package main

import (
	"database/sql"
	"log"
	"time"

	"github.com/gin-gonic/gin"
	"go-tzv/config"
	"go-tzv/database"
	"go-tzv/httpclient"
)

func main() {
	// 加载配置文件
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 连接数据库
	db, err := database.ConnectDB(cfg)
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	defer db.Close()

	// 创建 Gin 引擎
	r := gin.Default()

	// 启动价格更新协程
	go updatePrices(db)

	// 启动服务器
	if err := r.Run(":8080"); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

// updatePrices 更新价格信息
func updatePrices(db *sql.DB) {
	apiSymbols := []string{"btcusdt", "ethusdt", "usdcusdt", "ltcusdt", "dotusdt"} // 可添加更多币种
	proxyURL := ""                                                                 // 替换为实际的代理地址

	for {
		for _, apiSymbol := range apiSymbols {
			priceArr, err := httpclient.GetLastPriceInfo(apiSymbol, proxyURL)
			if err != nil {
				log.Printf("Failed to get price info for %s: %v", apiSymbol, err)
				continue
			}
			if priceArr != nil {
				err := database.UpdatePrice(db, apiSymbol, priceArr)
				if err != nil {
					log.Printf("Failed to update database for %s: %v", apiSymbol, err)
				}
			}
		}
		time.Sleep(500 * time.Millisecond)
	}
}
